﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO;
using System.Xml;

namespace GoogleReaderAccess
{
    public delegate void SubscriptionFetchFailedInternal(object sender, SubscriptionsEventArgs e);
    public delegate void SubscriptionReadyInternal(object sender, SubscriptionListData subscriptionData);

    public class SubscriptionList
    {
        public SubscriptionList(SessionServices ss)
        {
            session = ss;
        }

        public void getSubscriptionList()
        {
            try
            {
                string url = "http://www.google.com/reader/api/0/unread-count";

                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
                req.Method = "GET";
                req.Headers["Authorization"] = "GoogleLogin auth=" + session.Auth;

                WebRequestState state = new WebRequestState();
                state.Request = req;
                IAsyncResult res = (IAsyncResult)req.BeginGetResponse(new AsyncCallback(HandleSubscriptionList), state);
            }
            catch (WebException ex)
            {
                RaiseSubscriptionEvent(ex.Message);
                return;
            }
            catch (Exception ex)
            {
                RaiseSubscriptionEvent(ex.Message);
                return;
            }
            
        }

        private void HandleSubscriptionList(IAsyncResult asyncResult)
        {
            try
            {
                WebRequestState state = (WebRequestState)asyncResult.AsyncState;
                HttpWebRequest request = state.Request;
                HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult);
                Stream responseStream = response.GetResponseStream();
                StreamReader reader = new StreamReader(responseStream);
                string xml_response = reader.ReadToEnd();
                response.Close();
                parseXmlResponse(xml_response);
            }
            catch (WebException ex)
            {
                RaiseSubscriptionEvent(ex.Message);
                return;
            }
            catch (Exception ex)
            {
                RaiseSubscriptionEvent(ex.Message);
                return;
            }
        }

        private void RaiseSubscriptionEvent(string msg)
        {
            if (SubscriptionFailed != null)
            {
                SubscriptionsEventArgs e = new SubscriptionsEventArgs(msg);
                SubscriptionFailed(this, e);
            }           
        }

        private void parseXmlResponse(string xml)
        {
            if (SubscriptionReady != null)
            {
                try
                {
                    XmlReader r = XmlReader.Create(new StringReader(xml));
                    while (r.Read())
                    {
                        switch (r.NodeType)
                        {
                            case XmlNodeType.Element:
                                if (r.Name == "list")
                                    readList(r.ReadSubtree());
                                break;
                            default:
                                break;
                        }

                    }
                    SubscriptionListData ld = new SubscriptionListData(xml);
                    SubscriptionReady(this, ld);
                }
                catch (Exception ex)
                {
                    return;
                }
            }
        }

        private void readList(XmlReader r)
        {
            while (r.Read())
            {
                if (r.NodeType == XmlNodeType.Element && r.Name == "object")
                {
                    readFeed(r.ReadSubtree());
                }
            }
            r.Close();
        }

        private void readFeed(XmlReader r)
        {
            string feedUrl;
            int unReadCount = 0;
            long timeStamp = 0;
            bool readUrl, readCount, readStamp;
            while (r.Read())
            {
                if (r.NodeType == XmlNodeType.Element)
                {
                    if (r.Name == "string")
                    {
                        feedUrl = (string)r.ReadElementContentAs(typeof(string), null);
                    }
                    else if (r.Name == "number")
                    {
                        string name = r.GetAttribute(0);
                        string num = (string)r.ReadElementContentAs(typeof(string), null);
                        if (name == "count")
                            unReadCount = int.Parse(num);
                        else if (name == "newestItemTimestampUsec")
                            timeStamp = long.Parse(num);
                    }
                }
            }
            r.Close();
        }

        public event SubscriptionFetchFailedInternal SubscriptionFailed;
        public event SubscriptionReadyInternal SubscriptionReady;
        private SessionServices session;
    }
}
